package com.sojson.util.security.shiro.realm;

import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;

import lombok.extern.slf4j.Slf4j;

/**
 * 重写的私有方法,因为重写某些方法需要调用Shiro的私有方法,单独放出来(这个类的方法都没有修改)
 * 
 * @author liu
 * @date 2020-08-08
 */
@Slf4j
public abstract class AbstractCustomPrivateAuthorizingRealm extends AuthorizingRealm {

    private Cache<Object, AuthorizationInfo> authorizationCache;

    protected Cache<Object, AuthorizationInfo> getAvailableAuthorizationCache() {
        Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
        if (cache == null && isAuthorizationCachingEnabled()) {
            cache = getAuthorizationCacheLazy();
        }
        return cache;
    }

    private Cache<Object, AuthorizationInfo> getAuthorizationCacheLazy() {

        if (this.authorizationCache == null) {

            if (log.isDebugEnabled()) {
                log.info("No authorizationCache instance set.  Checking for a cacheManager...");
            }

            CacheManager cacheManager = getCacheManager();

            if (cacheManager != null) {
                String cacheName = getAuthorizationCacheName();
                if (log.isDebugEnabled()) {
                    log.info("CacheManager [" + cacheManager + "] has been configured.  Building "
                        + "authorization cache named [" + cacheName + "]");
                }
                this.authorizationCache = cacheManager.getCache(cacheName);
            } else {
                if (log.isDebugEnabled()) {
                    log.info("No cache or cacheManager properties have been set.  Authorization cache cannot "
                        + "be obtained.");
                }
            }
        }

        return this.authorizationCache;
    }

    @Override
    public void setAuthorizationCache(Cache<Object, AuthorizationInfo> authorizationCache) {
        this.authorizationCache = authorizationCache;
    }

    @Override
    public Cache<Object, AuthorizationInfo> getAuthorizationCache() {
        return this.authorizationCache;
    }

}